package com.wendyxie.sproutup.view

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.wendyxie.sproutup.databinding.ActivityParentPwdChangeBinding
import com.wendyxie.sproutup.db.SQLInitHelper
import com.wendyxie.sproutup.db.SQLUserHelper
import com.wendyxie.sproutup.entity.UserEntity
import com.wendyxie.sproutup.utils.SPUtil

class ParentPwdChangeActivity : AppCompatActivity() {

    private lateinit var binding: ActivityParentPwdChangeBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityParentPwdChangeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnConfirm.setOnClickListener {
            confirmPwd()
        }
    }

    private fun confirmPwd() {
        val oldPwd = binding.editOldPwd.getText()
        val newPwd = binding.editNewPwd.getText()
        // 1. 检查旧密码是否正确
        val userEntity = SQLUserHelper.queryBabyById(SPUtil.getBabyId(binding.root.context), SQLInitHelper(binding.root.context).openDatabase())
        if (userEntity.babyPwd != oldPwd) {
            // 旧密码错误
            Toast.makeText(binding.root.context, "旧密码错误", Toast.LENGTH_SHORT).show()
            return
        }
        // 2. 检查新密码
        if (newPwd.length < 4) {
            Toast.makeText(binding.root.context, "新密码长度必须为4位数字", Toast.LENGTH_SHORT).show()
            return
        }
        // 3. 修改密码
        SQLUserHelper.updateUserPwdById(SPUtil.getBabyId(binding.root.context), newPwd, SQLInitHelper(binding.root.context).openDatabase())
        // 4. 进入输入密码页面
        finish()
    }
}